<template>
  <el-form
    :model="addGoodsForm"
    :rules="addGoodsFormRules"
    ref="addGoodsFormRef"
    label-position="top"
  >
    <el-form-item label="商品名称" prop="goods_name">
      <el-input v-model="addGoodsForm.goods_name"></el-input>
    </el-form-item>
    <el-form-item label="商品价格" prop="goods_price">
      <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
    </el-form-item>
    <el-form-item label="商品重量" prop="goods_weight">
      <el-input v-model="addGoodsForm.goods_weight"></el-input>
    </el-form-item>
    <el-form-item label="商品数量" prop="goods_number">
      <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
    </el-form-item>
    <el-form-item label="商品分类">
      <el-cascader
        v-model="addGoodsForm.goods_cat"
        :show-all-levels="false"
        :options="goodsCateList"
        :props="goodsCateProps"
        @change="handleChange"
      ></el-cascader>
    </el-form-item>
  </el-form>
</template>

<script>
import { getGoodsCateAPI } from '@/api'
import EventBus from '@/event-bus'
export default {
  name: 'BasicInfo',
  inject: ['addGoodsForm'],
  data() {
    var checkNum = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error('数值不能小于零'))
      } else {
        callback()
      }
    }
    return {
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量不能为空', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空', trigger: 'blur' },
          { validator: checkNum, trigger: 'blur' }
        ]
      },
      goodsCateList: [],
      goodsCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      }
    }
  },
  created() {
    this.loadingGoodsCateList()
  },
  methods: {
    async loadingGoodsCateList() {
      try {
        const { data } = await getGoodsCateAPI()
        if (data.meta.status !== 200) {
          return this.$message.error('加载商品分类列表数据失败')
        }
        this.goodsCateList = data.data
        this.$message.success('加载商品分类列表数据成功')
      } catch (err) {
        this.$message.error('加载商品分类列表数据失败')
      }
    },
    //   商品分类改变
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        return (this.addGoodsForm.goods_cat = [])
      }
    },
    validBtn() {
      this.$refs.addGoodsFormRef.validate(valid => {
        if (!valid) return this.$message.error('请按要求填写基本信息')
      })
    }
  },
  mounted() {
    EventBus.$on('valid-form', () => {
      this.validBtn()
    })
  }
}
</script>

<style scoped lang="less"></style>
